<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Audio Upload with WebSocket</title>
</head>

<body>
<h1>上传音频文件并接收反馈</h1>

<!-- 文件选择 -->
<input type="file" id="audioFile" accept="audio/*"/>
<!-- 新增发送文件按钮 -->
<button id="sendFileButton" disabled>发送文件</button>

<script>
    // 创建 WebSocket 连接
    const ws = new WebSocket('ws://192.168.110.20:8888/ws/asr?connectId=eyJhbGciOiJIUzUxMiJ9.eyJsb2dpblVzZXJLZXkiOiI5ZTU5ZWRlOS0yMDczLTQ5MTgtOTBkNy0xZjYyNDYwYjI1M2UiLCJvcGVuVXNlcklkIjoiMTEwMjExNzgxNzI5MDc1MiJ9.GC6UfalpaRonVlZ4hHv4cIMnx-Ibi9_fEQYS_aATpdhZGujfgF4gQs79_7xUryY_OJ7oc3Mt3PLvTPKEVT1ilQ');

    // 打开连接时
    ws.onopen = () => {
        console.log('WebSocket连接已打开');
    };

    // 接收到服务器反馈时
    ws.onmessage = (event) => {
        // 处理从服务器返回的二进制数据
        const arrayBuffer = event.data;

        console.log('接收到的二进制数据:', event.data);

        // 你可以在此处做进一步处理，比如播放音频或显示信息等
    };

    // 连接关闭时
    ws.onclose = (event) => {
        console.log('WebSocket连接已关闭', event);
    };

    // 连接错误时
    ws.onerror = (error) => {
        console.error('WebSocket 错误:', error);
    };

    let selectedFile = null;

    // 选择文件时触发的事件
    document.getElementById('audioFile').addEventListener('change', (event) => {
        selectedFile = event.target.files[0];
        if (selectedFile) {
            // 启用发送按钮
            document.getElementById('sendFileButton').disabled = false;
        } else {
            // 禁用发送按钮
            document.getElementById('sendFileButton').disabled = true;
        }
    });

    // 发送文件按钮点击事件
    document.getElementById('sendFileButton').addEventListener('click', () => {
        if (selectedFile) {
            // 读取文件为 ArrayBuffer
            const reader = new FileReader();
            reader.onload = (e) => {
                const audioData = e.target.result;
                console.log('读取音频文件成功:', audioData);

                // 分块发送音频数据，每块 4 KB
                const chunkSize = 8000; // 每块大小为 4 KB
                const totalChunks = Math.ceil(audioData.byteLength / chunkSize);
                for (let i = 0; i < totalChunks; i++) {
                    const start = i * chunkSize;
                    const end = Math.min((i + 1) * chunkSize, audioData.byteLength);
                    const chunk = audioData.slice(start, end);

                    // 检查 WebSocket 连接是否已经打开
                    if (ws.readyState === WebSocket.OPEN) {
                        ws.send(chunk);
                        console.log(`音频数据块 ${i + 1} / ${totalChunks} 已发送到服务器`);
                    } else {
                        console.error('WebSocket 未连接');
                        break;
                    }
                }
            };
            reader.readAsArrayBuffer(selectedFile);
        }
    });
</script>
</body>

</html>